var $ = require('eui-mini.min.js');
var Decimal = require("decimal.js");

var ret={};

//产品价格计算器
ret.ProductPriceCounter={
    create:function () {
        var ppc={
            products:[]
        };
        //product包含产品必须信息
        // id 产品的id
        // saleprice
        // sku 如果启用sku并且选择了相应的sku，是此字段不为null，是个sku对象，sku对象包含saleprice/shippingcost
        // shippingcost 产品的运费对象
        // coupons 该产品的所有在有效期内的优惠券
        // num 件数
        ppc.addProduct=function (product) {
            var me = this;
            if( $.indexOfArray(product,me.products,function (a,b) {
                return $.toInt(a.id) === $.toInt(b.id)
            }) < 0){
                me.products.push( product )
            }
        };
        ppc.removeProduct=function (id) {
            var me = this;
            var index= $.indexOfArray(id,me.products,function (a,b) {
                return $.toInt(a) === $.toInt(b.id)
            });
            if( index >= 0 ){
                me.products.splice(index,1);
            }
        };
        //改变件数
        ppc.changeNum=function(productid,num){
            var me = this;
            var index= $.indexOfArray(productid,me.products,function (a,b) {
                return $.toInt(a) === $.toInt(b.id)
            });
            if( index >= 0 ){
                var product = me.products[index];
                product.num = num;
            }
        };
        //根据件数计算运费
        ppc.getShipFee=function(num,ship){

            var defcount = $.toInt(ship.defcount);
            var defcost = new Decimal(ship.defcost);
            var stepcount = $.toInt(ship.stepcount);
            var stepcost = new Decimal(ship.stepcost);
            var costfree = $.toInt(ship.costfree);

            var shipfee = new Decimal(0);
            if (!costfree) {//不包邮
                if (num >= defcount) shipfee.plus(defcost);
                num -= defcount;
                if (stepcount >= 1) {
                    shipfee.plus(new Decimal($.toInt((num + stepcount - 1) / stepcount) * stepcost));
                }

            }
            return shipfee.toNumber();
        };
        ppc.getProductShipFee=function(id){
            var me = this;
            var index= $.indexOfArray(id,me.products,function (a,b) {
                return $.toInt(a) === $.toInt(b.id)
            });
            if( index >= 0 ){
                var product = me.products[index];
                var ship = null;
                var num = $.toInt(product.num);

                if( product.sku ){
                    if( product.sku.shippingcost ) ship = product.sku.shippingcost;
                }
                if( !ship ){
                    if( product.shippingcost ) ship = product.shippingcost;
                }
                //运费
                if( ship )
                    return me.getShipFee(num,ship);
            }
            return 0;
        };
        ppc.getProductPrice=function(product,useCoupon){
            var me = this;
            var ship = null;
            var num = $.toInt(product.num);
            var productPrice=0;
            if( product.sku ){
                if( product.sku.shippingcost ) ship = product.sku.shippingcost;
            }
            if( !ship ){
                if( product.shippingcost ) ship = product.shippingcost;
            }
            //运费
            if( ship )
                productPrice += me.getShipFee(num,ship);
            //卖价
            var saleprice = 0;
            if( product.sku ){
                saleprice = $.toFloat(product.sku.saleprice);
            }else{
                saleprice = $.toFloat(product.saleprice);
            }
            productPrice +=num * saleprice;
            //优惠
            if( useCoupon ){
                var coupons = me.getProductCoupons(product.id);
                $.each(coupons,function (coupon) {
                    var count = $.toInt(coupon.matchnum);
                    if( count > 0 && num >= count ){
                        productPrice -= $.toFloat(coupon.money);
                    }
                    var money = $.toFloat(coupon.matchprice);
                    if( money > 0 && productPrice >= money){
                        productPrice -= $.toFloat(coupon.money);
                    }
                });

            }

            return productPrice;
        };
        //计算总价
        ppc.getTotalPrice=function () {
            var me = this;
            var total = 0;
            $.each(me.products,function (product) {
                //总价
                total += me.getProductPrice(product,true);
            });
            return total.toFixed(2);
        };
        //计算满足条件的优惠券
        ppc.getProductCoupons=function (id) {
            var me = this;
            var cs=[];//所有满足条件的优惠
            var index= $.indexOfArray(id,me.products,function (a,b) {
                return $.toInt(a) === $.toInt(b.id)
            });
            if( index >= 0 ){
                var product = me.products[index];
                var productPrice = me.getProductPrice(product,false);

                $.each(product.coupons,function (coupon) {
                    var count = $.toInt(coupon.matchnum);
                    if( count > 0 && product.num >= count){
                        var numCs = null;
                        var indexCs = -1;
                        $.each(cs,function (c,i) {
                            var x = $.toInt(c.matchnum);
                            if( x > 0 && product.num >= x ){
                                numCs = c;
                                indexCs = i;
                                return true;
                            }
                        });
                        //有同时满足数量的，则取最大的
                        if( indexCs >= 0 ){
                            if( count > $.toInt(numCs.matchnum)){
                                cs.push(coupon);
                            }
                        }else{
                            cs.push(coupon)
                        }
                    }else{
                        var m = $.toFloat(coupon.matchprice);
                        if( m > 0 && productPrice >= m ){

                            var numCs = null;
                            var indexCs = -1;
                            $.each(cs,function (c,i) {
                                var x = $.toFloat(c.matchprice);
                                if( x > 0 && productPrice >= x ){
                                    numCs = c;
                                    indexCs = i;
                                    return true;
                                }
                            });
                            //有同时满足价格的，则取最大的
                            if( indexCs >= 0 ){
                                if( m > $.toFloat(numCs.matchprice)){
                                    cs.push(coupon);
                                }
                            }else{
                                cs.push(coupon)
                            }
                        }
                    }
                })
            }
            return cs;
        };
        return ppc;
    }
};

//sku工具
ret.SkuTool={
    create:function () {
        return {
            //所有的可用sku,[{id,sn,icon,saleprice,marketprice,choices:[{choiceid,propid,skuid},...]},...]
            Skus:[],
            //所有用到的prop,[{id,name,style,choices:[{id,name,url},...]},...]
            //注意：choice分为“可用”、“不可用”、“已选”三种状态
            //可用 ： 当前sku具有该choice，可切换为选中状态
            //不可用：当前sku不具有该choice，但可以强制选中（将自动强制切换为该choice对应的sku）
            //已选：已经选中了该choice，所有已选的choice将唯一对应一个sku
            Props:[],
            //找到价格最低的sku
            findLowest:function () {
                var me = this;
                var p = -1;
                var sku=null;
                $.each(me.Skus,function (s) {
                    var p1 = $.toFloat(s.saleprice);
                    if( p < 0 ){
                        p = p1;
                        sku = s;
                    }else{
                        if( p1 < p ){
                            p = p1;
                            sku = s;
                        }
                    }
                });
                return sku;
            },
            //根据选中的choice找到匹配的sku
            findSku:function (arrChoice) {
                var me = this;
                var skuFound = null;
                $.each(me.Skus,function (sku) {
                    var match = true;
                    $.each(arrChoice,function (choice) {
                        if( !me.inSku(choice,sku)){
                            match = false;
                            return true;
                        }
                    });
                    if( match && arrChoice.length === sku.choices.length ){
                        skuFound = sku;
                        return true;
                    }
                });

                return skuFound;
            },
            //判断某个属性是否选中（只要它的某个choice被选中就代表该prop被选中）
            /*isPropChecked:function(prop,arrChoice){
                var me = this;
                var vLen = arrChoice.length;
                var vclen = prop.choices.length;
                for(var i=0;i<vclen;i++){
                    var id1 = $.toInt(prop.choices[i].id);
                    for(var j=0;j<vLen;j++){
                        var id2 = $.toInt(arrChoice[j]);
                        if( id1 === id2 ) return true;
                    }
                }
                return false;
            },
            //得到sku的所有可用prop
            getSkuProps:function(sku){
                var me = this;
                var ret=[];
                $.each(me.Props,function (prop) {
                    $.each(sku.choices,function (choice) {
                        var index=$.indexOfArray(choice,prop.choices,function (a,b) {
                            return $.toInt(choice.choiceid) === $.toInt(b.id)
                        });
                        if( index >= 0 ){
                            ret.push(prop);
                            return true;
                        }
                    })
                });
                return ret;
            },
            //根据当前choice找到对应的prop
            findCurProp:function(props,choiceid){
                var me = this;
                var vLen = props.length;
                for(var i=0;i<vLen;i++){
                    var prop = props[i];
                    var index=$.indexOfArray(choiceid,prop.choices,function (a,b) {
                        return $.toInt(a)===$.toInt(b.id);
                    });
                    if( index >= 0 ){
                        return prop;
                    }
                }
                return null;
            },*/
            //判断choice是否在prop中
            inProp:function(choiceid,prop){
                return $.indexOfArray(choiceid,prop.choices,function (a,b) {
                    return $.toInt(a)===$.toInt(b.id)
                })>=0;
            },
            //判断choice是否在sku中
            inSku:function(choiceid,sku){
                return $.indexOfArray(choiceid,sku.choices,function (a,b) {
                    return $.toInt(a)===$.toInt(b.choiceid)
                })>=0;
            },
            //判断choice是否在skus中
            inSkus:function(choiceid,skus){
                var me = this;
                return $.indexOfArray(choiceid,skus,function (a,b) {
                    return me.inSku(choiceid,b)
                })>=0;
            },
            //根据当前choice，查找所有可用的sku
            findSkus:function(choiceid){
                var me = this;
                var ret=[];
                $.each(me.Skus,function (sku) {
                    if( me.inSku(choiceid,sku)){
                        ret.push(sku);
                    }
                });
                return ret;
            },
            //查找同时包含choices的skus
            findChoicesSkus:function(choices){
                var me = this;
                var ret=[];
                $.each(me.Skus,function (sku) {
                    var match=true;
                    $.each(choices,function (c) {
                        if( !me.inSku(c,sku)){
                            match = false;
                            return true;
                        }
                    });
                    if( match ){
                        ret.push( sku );
                    }
                });
                return ret;
            },
            //根据当前选中的choice格式化其它选中的choice，包括：
            //1.如果某个prop中没有选中choice，则自动选中一个
            //2.如果某个prop中选中的choice不属于当前sku，则切换sku并自动选中一个choice
            formatChoices:function (curChoices,curChoiceid,curSku) {
                var me = this;
                var ret={
                    sku:null,//切换到的新sku
                    choices:[]//新的被选中的choice
                };

                //找一个最接近的sku
                var tmpChoices=[];
                tmpChoices.push(curChoiceid);//当前id必须入栈

                $.each(me.Props,function (prop) {
                    //跳过curChoiceid
                    if( !me.inProp(curChoiceid,prop)){
                        var choiceid = -1;
                        $.each(curChoices,function (choice) {
                            if( me.inProp(choice,prop)){
                                choiceid = $.toInt(choice);
                                return true;
                            }
                        });
                        if( choiceid > 0 ){
                            tmpChoices.push(choiceid);
                            if( me.findChoicesSkus(tmpChoices).length < 1 ){
                                tmpChoices.pop();
                                choiceid = -1;
                            }
                        }
                        if( choiceid < 0 ){
                            //一个一个地尝试
                            $.each(prop.choices,function (choice) {
                                tmpChoices.push(choice.id);
                                if( me.findChoicesSkus(tmpChoices).length > 0 ){
                                    return true;
                                }else{
                                    tmpChoices.pop();
                                }
                            });
                        }
                    }
                });
                var skus = me.findChoicesSkus(tmpChoices);
                if( skus.length > 0 ){
                    ret.sku = skus[0];
                    ret.choices = tmpChoices;
                }

                return ret;
            },
            //根据skuid得到规格名称
            getSkuNames:function (skuid,sep) {
                var me = this;
                if( sep===undefined) sep=" ";
                var arr=[];
                var sku = me.Skus[$.indexOfArray(skuid,me.Skus,function (a,b) {
                    return $.toInt(a) === $.toInt(b.id)
                })];
                $.each(sku.choices,function (c) {
                    $.each(me.Props,function (p) {
                        $.each(p.choices,function (pc) {
                            if( $.toInt(c.choiceid)===$.toInt(pc.id)){
                                arr.push(pc.name)
                            }
                        })
                    })
                });
                return arr.join(sep);
            }
        };
    }
};

//sku价格计算器
ret.SkuPriceTool={
    create:function (oSku,num) {
        return {
            sku:oSku,
            num:num,
            //计算运费
            getShipFee:function () {
                var me = this;
                var ship = me.sku.shippingcost;
                var shipfee = 0;
                if( ship && $.isObject(ship)){
                    var defcount = $.toInt(ship.defcount);
                    var defcost = $.toFloat(ship.defcost);
                    var stepcount = $.toInt(ship.stepcount);
                    var stepcost = $.toFloat(ship.stepcost);
                    var costfree = $.toInt(ship.costfree);
                    var num = me.num;

                    if (!costfree) {//不包邮
                        if (num >= defcount) shipfee += defcost;
                        num -= defcount;
                        if (stepcount >= 1) {
                            shipfee += $.toInt((num + stepcount - 1) / stepcount) * stepcost;
                        }

                    }
                }

                return $.toFloat(shipfee);
            },
            //计算价格（小计）
            getTotalPrice:function () {
                var me = this;
                var totalprice=0;
                /*
                var coupons = me.sku.coupons;
                if( coupons && $.isArray(coupons)){
                    var cs=[];//所有满足条件的优惠
                    $.each(coupons,function (coupon) {
                        var count = $.toInt(coupon.matchnum);
                        if( count > 0 && me.num >= count){
                            var numCs = null;
                            var indexCs = -1;
                            $.each(cs,function (c,i) {
                                var x = $.toInt(c.matchnum);
                                if( x > 0 && product.num >= x ){
                                    numCs = c;
                                    indexCs = i;
                                    return true;
                                }
                            });
                            //有同时满足数量的，则取最大的
                            if( indexCs >= 0 ){
                                if( count > $.toInt(numCs.matchnum)){
                                    cs.push(coupon);
                                }
                            }else{
                                cs.push(coupon)
                            }
                        }else{
                            var m = $.toFloat(coupon.matchprice);
                            if( m > 0 && productPrice >= m ){

                                var numCs = null;
                                var indexCs = -1;
                                $.each(cs,function (c,i) {
                                    var x = $.toFloat(c.matchprice);
                                    if( x > 0 && productPrice >= x ){
                                        numCs = c;
                                        indexCs = i;
                                        return true;
                                    }
                                });
                                //有同时满足价格的，则取最大的
                                if( indexCs >= 0 ){
                                    if( m > $.toFloat(numCs.matchprice)){
                                        cs.push(coupon);
                                    }
                                }else{
                                    cs.push(coupon)
                                }
                            }
                        }
                    })
                }
                */
            }
        }
    }
};

//购物车工具
ret.CartTool={
    create:function () {
        return {
            Carts:[],
            Selected:[],//[{id,num}]
            //根据id得到下标
            getIndex:function (id) {
                var me = this;
                return $.indexOfArray(id,me.Carts,function (a,b) {
                    return $.toInt(a) === $.toInt(b.id)
                })
            },
            //添加选中项
            add:function(id,num){
                this.Selected.push({id:id,num:num})
            },
            //清空选中项
            clear:function(){
                this.Selected=[]
            },
            //统计商品小计
            getSubTotal:function (id) {
                var me = this;

                var total=0;

                var cart = me.Carts[me.getIndex(id)];

                total += $.toFloat(cart.saleprice)*$.toInt(cart.num);
                total += $.toFloat(me.getShipFee(id));
                var matchs = me.getMatchCoupons(id);
                $.each(matchs,function (m) {
                    total -= $.toFloat(m.money)
                });
                return total;
            },
            //统计合计
            getTotal:function () {
                var me = this;

                var total=0;
                $.each(me.Selected,function (c) {
                    total += me.getSubTotal(c.id)
                });
                return total;
            },
            //是否全部选中了
            isSelectedAll:function () {
                var me = this;
                return me.Selected.length === me.Carts.length;
            },
            //得到满足条件的优惠券
            getMatchCoupons:function (id) {
                var me = this;
                var ppc = ret.ProductPriceCounter.create();

                var cart = me.Carts[me.getIndex(id)];
                var product={};
                product.id = cart.productid;
                product.saleprice = cart.saleprice;
                if( cart.sku && $.isObject(cart.sku)) product.sku = cart.sku;
                if( cart.shippingcost && $.isObject(cart.shippingcost)) product.shippingcost = cart.shippingcost;
                product.num = cart.num;
                product.coupons = cart.coupons;
                ppc.addProduct(product);
                //更新满足条件的优惠券信息
                return ppc.getProductCoupons(cart.productid);
            },
            //计算运费
            getShipFee:function (id) {
                var me = this;
                var ppc = ret.ProductPriceCounter.create();

                var cart = me.Carts[me.getIndex(id)];
                var product={};
                product.id = cart.productid;
                product.saleprice = cart.saleprice;
                if( cart.sku && $.isObject(cart.sku)) product.sku = cart.sku;
                if( cart.shippingcost && $.isObject(cart.shippingcost)) product.shippingcost = cart.shippingcost;
                product.num = cart.num;
                product.coupons = cart.coupons;
                ppc.addProduct(product);
                //更新满足条件的优惠券信息
                return ppc.getProductShipFee(cart.productid);
            }
        }
    }
};

module.exports = ret;